package org.jeecg.modules.monitoring.j_monitoring.job.software;


import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.FileUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * MySql数据库数据的备份
 * @Author: cn2008tv
 */

@Slf4j
public class BackupMySqlDatabaseJob implements Job {

//      # 备份数据库配置
//    database:
//    mysqldump: D:\Software\mysql-8.0.12\bin\mysqldump
//    username: root
//    password: 123
//    name: j_monitoring
//    backupDataPath: D:\data\
    @Value("${jeecg.database.mysqldump}")
    private String mysqldump = "D:\\Software\\mysql-8.0.12\\bin\\mysqldump";

    @Value("${jeecg.database.username}")
    private String username = "root";

    @Value("${jeecg.database.password}")
    private String password = "123";

    @Value("${jeecg.database.name}")
    private String name = "j_monitoring";

    @Value("${jeecg.database.host}")
    private String host = "localhost";

    @Value("${jeecg.database.port}")
    private String port = "3306";

    @Value("${jeecg.database.backupDataPath}")
    private String backupDataPath = "D:\\data\\";
    /***
     * 执行
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        // 设置备份文件路径和名称
        String backupFilePath = "/path/to/backupfile.sql";
        backupFilePath = backupDataPath;
        if(!backupFilePath.endsWith(File.separator)){
            backupFilePath = backupFilePath + File.separator;
        }

        String week = DateUtils.dateToWeek("");
        backupFilePath = backupFilePath + week + ".sql";
        File file = new File(backupFilePath );
        if (file.exists()) {
            // 创建文件根目录
            file.delete();
        }
        // 构造备份命令
        List<String> command = new ArrayList<>();
        //command.add("/usr/bin/mysqldump"); // mysqldump命令所在位置
        command.add(mysqldump);
        command.add("--user=" + username); // 添加用户名参数
        command.add("--password=" + password); // 添加密码参数
        command.add("--host=" + host); // 添加主机参数
        command.add("--port=" + port); // 添加端口参数
        command.add("--result-file=" + backupFilePath); // 添加结果输出文件参数
        command.add(name); // 添加要备份的数据库名称

        // 执行备份命令
        try {
            Process process = new ProcessBuilder().command(command).start();
            int exitCode = process.waitFor();

            if (exitCode == 0) {
                System.out.println("数据库备份成功！");
            } else {
                System.out.println("数据库备份失败！");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}
